package sncf.server;

import java.util.List;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;

import com.sun.mail.smtp.SMTPTransport;

public class EmailService {

	// FIELDS
	private static EmailService instance;

	private static final String DEFAULT_HOST = "smtp.gmail.com";
	private static final int DEFAULT_HOST_PORT = 587;
	private static final String DEFAULT_USER = "sncfdumper@gmail.com";
	private static final String DEFAULT_PASSWORD = "dumper#train01";
	private static final String DEFAULT_FROM = "sncfdumper@gmail.com";

	// CONSTRUCTORS
	private EmailService() {

	}

	// METHODS
	public static EmailService getInstance() {
		synchronized (EmailService.class) {
			if (instance == null) {
				instance = new EmailService();
			}
		}
		return instance;
	}

	public void sendSimpleMail(List<String> toList, List<String> ccList,
			String subject, String bodyContent, boolean htmlMessage) {
		if (toList == null || toList.isEmpty()) {
			throw new IllegalArgumentException(
					"The destination email list is null or empty");
		}

		// Get system properties
		Properties properties = System.getProperties();

		// Setup mail server
		final String protocol = "smtp";

		properties.put("mail." + protocol + ".starttls.enable", "true");
		properties.put("mail." + protocol + ".socketFactory.class",
				"javax.net.ssl.SSLSocketFactory");

		// Get the default Session object.
		Session session = Session.getDefaultInstance(properties);

		try {
			// Create a default MimeMessage object.
			MimeMessage message = new MimeMessage(session);

			// Set From: header field of the header.
			message.setFrom(new InternetAddress(DEFAULT_FROM, "Sncf Dumper"));

			// Set To an CC: header field of the header.
			Address[] toAddresses = new InternetAddress[toList.size()];
			int i = 0;
			for (String toAddress : toList) {
				toAddresses[i] = new InternetAddress(toAddress);
				i++;
			}
			message.addRecipients(Message.RecipientType.TO, toAddresses);

			if (ccList != null && !ccList.isEmpty()) {
				Address[] ccAddresses = new InternetAddress[ccList.size()];
				int j = 0;
				for (String ccAddress : ccList) {
					ccAddresses[j] = new InternetAddress(ccAddress);
					j++;
				}
				message.addRecipients(Message.RecipientType.CC, ccAddresses);
			}

			// Set Subject: header field
			message.setSubject(subject);

			// Now set the actual message
			if (htmlMessage) {
				message.setDataHandler(new DataHandler(new ByteArrayDataSource(
						bodyContent, "text/html")));
			} else {
				message.setText(bodyContent);
			}

			// Send message
			SMTPTransport t = (SMTPTransport) session.getTransport(protocol);
			t.connect(DEFAULT_HOST, DEFAULT_HOST_PORT, DEFAULT_USER,
					DEFAULT_PASSWORD);

			t.sendMessage(message, message.getAllRecipients());
			System.out.println("All email sent successfully!!");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void sendMailWithAttachement(List<String> toList,
			List<String> ccList, String subject, String bodyContent,
			boolean htmlMessage, List<String> filePathList) {
		// Get system properties
		Properties properties = System.getProperties();

		// Setup mail server
		final String protocol = "smtp";

		properties.put("mail." + protocol + ".starttls.enable", "true");
		properties.put("mail." + protocol + ".socketFactory.class",
				"javax.net.ssl.SSLSocketFactory");

		// Get the default Session object.
		Session session = Session.getDefaultInstance(properties);

		try {
			// Create a default MimeMessage object.
			MimeMessage message = new MimeMessage(session);

			// Set From: header field of the header.
			message.setFrom(new InternetAddress(DEFAULT_FROM, "Sncf Dumper"));

			// Set To an CC: header field of the header.
			Address[] toAddresses = new InternetAddress[toList.size()];
			int i = 0;
			for (String toAddress : toList) {
				toAddresses[i] = new InternetAddress(toAddress);
				i++;
			}
			message.addRecipients(Message.RecipientType.TO, toAddresses);

			if (ccList != null) {
				Address[] ccAddresses = new InternetAddress[ccList.size()];
				int j = 0;
				for (String ccAddress : ccList) {
					ccAddresses[j] = new InternetAddress(ccAddress);
					j++;
				}
				message.addRecipients(Message.RecipientType.CC, ccAddresses);
			}

			// Set Subject: header field
			message.setSubject(subject);

			// Now set the actual message
			if (filePathList != null && !filePathList.isEmpty()) {
				Multipart msgParts = new MimeMultipart();

				MimeBodyPart bodyPart = new MimeBodyPart();
				if (htmlMessage) {
					bodyPart.setDataHandler(new DataHandler(
							new ByteArrayDataSource(bodyContent, "text/html")));
				} else {
					bodyPart.setText(bodyContent);
				}
				msgParts.addBodyPart(bodyPart);

				for (String filePath : filePathList) {
					MimeBodyPart part = new MimeBodyPart();
					part.attachFile(filePath);
					msgParts.addBodyPart(part);
				}

				message.setContent(msgParts);
			} else {
				if (htmlMessage) {
					message.setDataHandler(new DataHandler(
							new ByteArrayDataSource(bodyContent, "text/html")));
				} else {
					message.setText(bodyContent);
				}
			}

			// Send message
			SMTPTransport t = (SMTPTransport) session.getTransport(protocol);
			t.connect(DEFAULT_HOST, DEFAULT_HOST_PORT, DEFAULT_USER,
					DEFAULT_PASSWORD);

			t.sendMessage(message, message.getAllRecipients());
			System.out.println("Sent email successfully....");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
